package models

import (
	"encoding/json"
	"github.com/beego/beego/v2/client/orm"
	"strings"
)

type OptometryQueryParam struct {
	BaseQueryParam
	ArchivesId int64
	Filter     string
	IsOptician string //配镜状态
	Optid      int64
	StartDate  int64
	EndDate    int64
	Depid      int64
	OptNotId   string
	Deps       []string
}

type Optometry struct {
	Id             int64
	DepartmentId   int64
	Archives       *Archives `orm:"rel(fk)"`
	DocumentNumber string
	Optometrist    string
	Doctor         string
	FormType       string                                                     //来源
	Chufang        string                            `orm:"-" json:"-"`       //验光处方
	ChufangData    map[string]map[string]interface{} `orm:"-" json:"chufang"` //验光处方
	CreatedAt      int64
	UpdatedAt      int64
	CreatedBy      string
	UpdatedBy      string
	Status         int
	IsOptician     int
	Remarks        string
}

func (a *Optometry) TableName() string {
	return OptometryTableName()
}

func OptometryTableName() string {
	return TableName("ar_optometry")
}

//获取单条验光信息

func GetOptometryById(id int64) (*Optometry, error) {

	query := orm.NewOrm().QueryTable(OptometryTableName()).RelatedSel("Archives")

	data := new(Optometry)

	err := query.Filter("id", id).One(data)

	return data, err
}

func CreateOptometryDocumentNumber(c *BackendUser) string {
	return CreatePk()
}

/**
* 添加验光信息
 */
func OptometryAdd(a *Optometry) (int64, error) {
	a.Status = 1
	a.IsOptician = 0
	to,_ := orm.NewOrm().Begin()
	if _, err := to.Insert(a); err != nil {
		to.Rollback()
		return 0, err
	}

	//处方处理
	opt_data := make([]*OptometryData, 0)
	if len(a.Chufang) > 0 {
		if err := json.Unmarshal([]byte(a.Chufang), &opt_data); err != nil {
			to.Rollback()
			return 0, err
		}
		for k, _ := range opt_data {
			opt_data[k].Optometry = a
		}
		if _, err := to.InsertMulti(len(opt_data), opt_data); err != nil {
			to.Rollback()
			return 0, err
		}
	}
	to.Commit()
	return a.Id, nil
}

//修改验光信息
func (a *Optometry) OptometryEdit(fileds ...string) error {
	to,_ := orm.NewOrm().Begin()
	if _, err := to.Update(a, fileds...); err != nil {
		to.Rollback()
		return err
	}
	if err := UpdateOptometryDataForOptId(to, a.Id, a.Chufang); err != nil {
		to.Rollback()
		return err
	}
	to.Commit()
	return nil
}

func OptometryList(param *OptometryQueryParam) []*Optometry {

	query := orm.NewOrm().QueryTable(OptometryTableName())
	if param.ArchivesId > 0 {
		query = query.Filter("archives_id", param.ArchivesId)
	}
	if param.Optid > 0 {
		query = query.Filter("id", param.Optid)
	}
	if len(param.Deps) > 0 {
		query = query.Filter("department_id__in", param.Deps)
	} else {
		query = query.Filter("department_id", param.Depid)
	}

	data := make([]*Optometry, 0)
	query.OrderBy("-id").All(&data)

	return data
}

//带分页列表
func OptometryPageList(params *OptometryQueryParam) ([]*Optometry, int64) {

	query := orm.NewOrm().QueryTable(OptometryTableName()).RelatedSel()
	data := make([]*Optometry, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()

	if params.Filter != "" {
		cond = cond.Or("Archives__mobile__contains", params.Filter).Or("document_number__contains", params.Filter).Or("Archives__Number", params.Filter)
	}
	if params.StartDate > 0 && params.EndDate > 0 { //落单时间
		cond = cond.AndCond(cond.And("created_at__gte", params.StartDate).And("created_at__lte", params.EndDate))
	}

	query = query.SetCond(cond)

	if len(params.IsOptician) > 0 {
		query = query.Filter("is_optician", params.IsOptician)
	}
	if params.ArchivesId > 0 {
		query = query.Filter("archives_id", params.ArchivesId)
	}
	if len(params.OptNotId) > 0 {
		query = query.Exclude("id__in", strings.Split(params.OptNotId, ","))
	}

	query = query.Filter("status", 1)

	if len(params.Deps) > 0 {
		query = query.Filter("department_id__in", params.Deps)
	} else {
		query = query.Filter("department_id", params.Depid)
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total
}

//删除指定验光信息
func OptometryDelete(id int64) error {
	to,_ := orm.NewOrm().Begin()

	if _, err := to.QueryTable(OptometryTableName()).Filter("id", id).Filter("department_id", CurLoginUserInfo.DepartmentId).Delete(); err != nil {
		to.Rollback()
		return err
	}
	if _, err := to.Raw("DELETE FROM "+OptometryDataTableName()+" WHERE optometry_id=?", id).Exec(); err != nil {
		to.Rollback()
		return err
	}
	to.Commit()
	return nil
}

func queryOptometryTimeSoltSeter(starttime, endtime int64) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(OptometryTableName())

	cond := orm.NewCondition()
	cond = cond.And("status", 1).AndCond(cond.And("created_at__gte", starttime).And("created_at__lte", endtime))
	query = query.SetCond(cond)

	return query
}

//按时间段获取验光数据
func QueryOptometryTimeSoltSeter(curuser *BackendUser, starttime, endtime int64) []*Optometry {

	data := make([]*Optometry, 0)

	queryOptometryTimeSoltSeter(starttime, endtime).Filter("department_id", curuser.DepartmentId).All(&data)

	return data
}

//按时间段获取验光count
func QueryOptometryTimeSoltSeterCount(curuser *BackendUser, starttime, endtime int64) int64 {

	count, _ := queryOptometryTimeSoltSeter(starttime, endtime).Filter("department_id", curuser.DepartmentId).Count()

	return count
}
